package com.lc.projects.unit.thread.part04.test1;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

//运行多个任务 并处理所有结果 ExecutorService
public class Test3 {
	public static void main(String[] args) {
		ExecutorService executor = Executors.newCachedThreadPool();
		List<Task1> taskList = new ArrayList<>();
		for (int i = 0; i < 3; i++) {
			Task1 task = new Task1(i + "");
			taskList.add(task);
		}
		List<Future<Result>> resultList = new ArrayList<>();
		try {
			resultList = executor.invokeAll(taskList);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		executor.shutdown();

		System.out.println("Main: printing the result.");
		for (int i = 0; i < resultList.size(); i++) {
			Future<Result> future = resultList.get(i);
			try {
				Result result = future.get();
				System.out.println(result.getName() + ":" + result.getValue());
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}
}

class Result {
	private String name;
	private int value;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getValue() {
		return value;
	}

	public void setValue(int value) {
		this.value = value;
	}

}

class Task1 implements Callable<Result> {
	private String name;

	public Task1(String name) {
		super();
		this.name = name;
	}

	@Override
	public Result call() throws Exception {
		System.out.println("Starting..." + this.name);
		try {
			long duration = (long) (Math.random() * 10);
			System.out.println(this.name + " wait for result during " + duration);
			TimeUnit.SECONDS.sleep(duration);
		} catch (Exception e) {
			e.printStackTrace();
		}
		int value = new Random().nextInt(1000);
		Result result = new Result();
		result.setName(this.name);
		result.setValue(value);
		return result;
	}

}
